package cn.wolfcode.trip.app.controller;


import cn.wolfcode.trip.base.domain.Product;
import cn.wolfcode.trip.base.domain.ProductOrder;
import cn.wolfcode.trip.base.service.IProductOrderService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/** tiger
 *
 * 查询购物车商品控制器
 */
@RestController
@RequestMapping("/productOrders")
public class ProductOrderController {

    @Autowired
    private IProductOrderService productOrderService;

    @PostMapping
    public ProductOrder saveProductOrder(ProductOrder productOrder, @RequestParam("productInfo") String[] productInfo){
        List<Map> list = new ArrayList<>();
        for (String str1 : productInfo) {
            Map<String, Object> map = new HashMap<>();
            String[] keyAndValueArr = str1.split(";");
            for (String str2 : keyAndValueArr) {
                String[] keyAndValue = str2.split(":");
                map.put(keyAndValue[0],Integer.valueOf(keyAndValue[1]));
            }
            list.add(map);
        }
        JSONResult jsonResult= new JSONResult();
        try {
            ProductOrder result = productOrderService.saveProductOrder(productOrder);
            for (Map map : list) {
                map.put("orderId",productOrder.getId());
                productOrderService.saveConnections(map);
            }
            return result;
        } catch (Exception e) {
            jsonResult.mark("操作失败,稍后再试");
            e.printStackTrace();
        }
        return null;
    }

    @PostMapping("/updateOrderState")
    public Object updataState(ProductOrder productOrder){
       JSONResult jsonResult= new JSONResult();
        try {
            ProductOrder result = productOrderService.saveProductOrder(productOrder);
        } catch (Exception e) {
            jsonResult.mark("操作失败");
            e.printStackTrace();
        }
        return jsonResult;
    }

    /**
     * 根据订单id获取订单内容
     */
    @GetMapping("/{orderId}")
    public ProductOrder selectByOrderId(@PathVariable Long orderId){
        return productOrderService.selectByOrderId(orderId);
    }

}
